<template>
    <view class="background">

        <view class="search">
            <image src="../../static/images/servers/mipmap-xxxhdpi/1.png"></image>&nbsp;
            <input type="text" placeholder="输入省份城市或服务器搜索" @input="handleInput" @focus="handleSearch">
        </view>

        <view class="select">
            <view class="city">
                <scroll-view class="scroll-view" scroll-y="true">
                    <view
                        class="scroll-item"
                        v-for="(category, categoryIndex) in servers"
                        :key="categoryIndex"
                        @click="selectCategory(categoryIndex)"
                        :class="{ 'active-category': selectedCategoryIndex === categoryIndex }"
                        data-index="{{categoryIndex}}">
                        {{ category.name }}
                    </view>
                </scroll-view>
            </view>
            <view class="server">
                <scroll-view scroll-y="true" class="scroll-view">
                    <view
                        class="server-item"
                        v-for="(server, serverIndex) in getServerListByCategory(selectedCategoryIndex)"
                        :key="serverIndex">
                        {{ server.name }}
                    </view>
                </scroll-view>
            </view>
        </view>

    </view>
</template>

<script setup>
    import { onMounted, ref } from 'vue';
    import { getList } from "@/api/list.js";
    import { onShow } from "@dcloudio/uni-app";

    const servers = ref([]); // 所有服务器
    const selectedCategoryIndex = ref(0); // 用于记录当前选中的类别索引
    const searchInputValue = ref(''); // 用于保存搜索框输入的内容

    onMounted(() => {
        goToList();
    });

    let isFirstLoad = ref(true);
    onShow(() => {
        if (isFirstLoad && uni.getStorageSync('token')) {
            goToList();
            isFirstLoad = false;
        }
    })

    // 调用服务器列表接口
    const goToList = async () => {
        try {
            const res = await getList();
            if (res.code === 1) {
                servers.value = res.data;
                console.log('服务器列表获取成功');
            } else {
                console.error('服务器列表获取失败：', res);
            }
        } catch (error) {
            console.error('登录过程中出现错误：', error.message);
        }
    };

    // 处理类别点击事件
    const selectCategory = (index) => {
        selectedCategoryIndex.value = index;
    };

    // 根据选中的类别索引获取对应的服务器列表
    const getServerListByCategory = (categoryIndex) => {
        return categoryIndex === null? [] : servers.value[categoryIndex] && servers.value[categoryIndex].server;
    };
	
	// 搜索框获得焦点时 调用函数并传入当前搜索框的值
	const handleSearch = () => {
	    const currentValue = searchInputValue.value;
	    handleInput({ detail: { value: currentValue } });
	};

    // 处理搜索框输入内容变化的函数
	const handleInput = (e) => {
    searchInputValue.value = e.detail.value;
    let foundIndex = null;
    // 先遍历servers数据查找匹配的类别名称
    for (let i = 0; i < servers.value.length; i++) {
        const category = servers.value[i];
        if (category.name === searchInputValue.value) {
            foundIndex = i;
            break; // 找到匹配的类别名称，先记录索引并退出这个循环
        }
    }
    if (foundIndex === null) {
        // 在类别名称中没找到匹配，再遍历服务器列表里的每个服务器名称查找匹配
        for (let categoryIndex = 0; categoryIndex < servers.value.length; categoryIndex++) {
            const category = servers.value[categoryIndex];
            const serverList = category.server || [];
            for (let serverIndex = 0; serverIndex < serverList.length; serverIndex++) {
                const server = serverList[serverIndex];
                if (server.name === searchInputValue.value) {
                    foundIndex = categoryIndex;
                    break; // 找到匹配的服务器名称，记录所属类别索引并退出内层循环
                }
            }
            if (foundIndex!== null) {
                break; // 找到匹配后就直接退出外层循环
            }
        }
    }
    // 搜索值为空或者未搜索到匹配内容 则将恢复为当前选中的类别索引
    if (searchInputValue.value === '' || foundIndex === null) {
        foundIndex = selectedCategoryIndex.value;
    }
    selectedCategoryIndex.value = foundIndex;

    if (foundIndex!== null) {
        // 当找到匹配项时，使用uni.pageScrollTo滚动到距离顶部90px的位置（可按需调整）
        uni.pageScrollTo({
            scrollTop: 90,
            duration: 300
        });
    }
};

</script>

<style lang="scss" scoped>
.background {
    background-color: #ffffff;
    width: 100vw;
    height: 100vh;
    padding-top: 20px;
}

.search {
    display: flex;
    // justify-content: center;
    align-items: center;
    padding-left: 20px;
    font-size: 20px;
    width: 80%;
    height: 50px;
    margin: 0 auto;
    margin-bottom: 20px;
    // margin-top: 40px;
    background-color: #F4F7F9;
    border-radius: 50px;
}

.search image {
    width: 15px;
    height: 15px;
}

.select {
    // background-color: #ffaaff;
    width: 100vw;
    height: calc(100vh - 90px);
    display: flex;
}

.city {
    width: 120px;
    height: 100%;
    background-color: #F4F7F9;
    padding: 20px 0 0px 0;
}

.scroll-view {
    height: 100%;
}

.scroll-item {
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.active-category {
    background-color: #ffffff;
    border-left: 3px solid #318BED;
    color: #318BED;
    // border-left-style: double;
}

.server {
    width: calc(100vw - 120px);
    height: 100%;
    background-color: #ffffff;
    transition: background-color 0.3s ease;
    padding: 20px 0 0px 0;
    // display: flex;
    // flex-direction: column;
    // align-items: center;
    // justify-content: flex-start;
}

.server-item {
    width: 85%;
    height: 50px;
    display: flex;
    align-items: center;
    text-align: left;
    margin-bottom: 10px;
    padding-left: 20px;
    // background-color: #F4F7F9;
    border-bottom: #F0F1F5 1px solid;

}
</style>